#!/usr/bin/python
import MuConnection, MuNetworkConfiguration, MuTestApi, MuRestApi, time, sys, getopt 

USERNAME = 'admin'
PASSWORD = ''
MU = ''

#get the username and password
args = sys.argv[0:]
try:
    options, remainder = getopt.getopt(sys.argv[1:], "u:p:i:", ["username=", "password=","ipaddress="])
except getopt.GetoptError, err:
    # print help information and exit:
    print str(err) # will print something like "option -a not recognized"
    usage()
    sys.exit(2)
for o, p in options:
    if o in ("-u","--username"):
     	USERNAME = p
    elif o in ("-p", "--password"):
     	PASSWORD = p
    elif o in ("-i", "--ipaddress"):
        MU = p


myMuConnection = MuConnection.MuConnection("https://"+MU,USERNAME,PASSWORD)

V6andV4_UUID = "d0b9788c-32a0-4e42-a516-415e914d6b9d"
V4Only_UUID = "44c95ea3-8b2e-47a8-b6b8-12903f2de07e"

scenarioUUID = V4Only_UUID
#scenarioUUID = V6andV4_UUID

V4Only_TemplateName = 'HTTP Proxy IPv4 to IPv4.xml'
V6andV4_TemplateName = 'HTTP Proxy IPv6 to IPv4.xml'

scenarioTemplate = V4Only_TemplateName
#scenarioTemplate = V6andV4_TemplateName

testSuiteUUID = "c38162c7-bf74-4c55-84fa-44602dc3bb89"
#testSuiteUUID = "45f59fed-bba7-4e03-a4cd-422b113779cc"
csvFileName = "MyCsv.csv"


#what sections will we run:
#capture pcaps while testing
doPcaps = False
# clear all sessions at start of testing (affects FX only)
clearAllAtStart = False
# run with testSuite and template on the Mu 
runAllFromMu = False
# run tests from local csv and scenario template
runFromLocalFiles = False
# export a CSV file
csvExport = False
#execute final close all sessions
finalClose = False

myTestApi = MuTestApi.MuTestApi(myMuConnection)

myTestApi.VERBOSE = False
myMuConnection.VERBOSE = False

#used to capture pcaps
myRestApi = MuRestApi.MuRestApi(myMuConnection)
pcapInterface = 'a1'
pcapName = 'myTestApiPacketCap.pcap'

# do pcap for troubleshooting
if doPcaps:
	response = myRestApi.runCapture(pcapInterface)
	jobId = response.getJobid()
	time.sleep(1)

# global test api commands
if clearAllAtStart:
	myTestApi.getAllSessions()
	myTestApi.closeAllSessions()
	


# run test from saved templates on the Mu
if runAllFromMu:
	myTestApi.newSession()
	# bad uuid 
	myTestApi.loadScenario("19191-0001-1223-BAD-UUID")
	# uuid is valid but not on found on te Mu
	myTestApi.loadScenario("d0b9788c-32a0-4e42-a506-415e914d6b9d")
	myTestApi.loadScenario(scenarioUUID)
	myTestApi.getHosts()
	myTestApi.setHost("HttpClient","a1")
	myTestApi.setHost("UnTrustedPort","a2")
	myTestApi.setHost("TrustedPort","b1")
	myTestApi.setHost("HttpServer","b2")
	myTestApi.getChannels()
	myTestApi.setChannels('channel','multicast_router')
	myTestApi.setChannels('channel_1','multicast_router')
	myTestApi.getOptions()
	# set scenario_user_options.http_method to NOGO forcing verrify fail
	myTestApi.setOptions("scenario_user_options.http_method","NOGO")
	# prepare test with options
	myTestApi.setupTest()
	# verify will fail
	myTestApi.verifyScenario()
	# set io.timeout to something workable
	myTestApi.setOptions("scenario_user_options.http_method","GET")
	# update test options with cahnges
	myTestApi.setupTest()
	# verify will pass
	myTestApi.verifyScenario()
	myTestApi.getTestSuiteStatus()
	myTestApi.runTestSuite(testSuiteUUID)
	time.sleep(1)
	loop = True
	while loop:
		response = myTestApi.getTestSuiteStatus()
		if response.getMessage() == "Done":
			loop = False
		time.sleep(2)
	response = myTestApi.getTestSuiteResults()
	resultsList = response.getRetrievedObject()
	for myResult in resultsList:
		print myResult
	myTestApi.tearDownTest()
	myTestApi.closeSession()

# run test from csv file and template file by importing to Mu test suite template and scenario template
if runFromLocalFiles:
	response = myRestApi.importTemplates(scenarioTemplate)
	scenarioUUID = response.getUUID()
	print "The UUID = " + scenarioUUID
	myTestApi.newSession()
	myTestApi.loadScenario(scenarioUUID)
	myTestApi.getHosts()
	myTestApi.setHost("HttpClient","a1")
	myTestApi.setHost("UnTrustedPort","a2")
	myTestApi.setHost("TrustedPort","b1")
	myTestApi.setHost("HttpServer","b2")
	myTestApi.getChannels()
	myTestApi.setChannels('channel','multicast_router')
	myTestApi.setChannels('channel_1','multicast_router')
	myTestApi.getOptions()
	# set scenario_user_options.http_method to NOGO forcing verrify fail
	myTestApi.setOptions("scenario_user_options.http_method","NOGO")
	# prepare test with options
	myTestApi.setupTest()
	# verify will fail
	myTestApi.verifyScenario()
	# set io.timeout to something workable
	myTestApi.setOptions("scenario_user_options.http_method","GET")
	# update test options with cahnges
	myTestApi.setupTest()
	# verify will pass
	myTestApi.verifyScenario()
	myTestApi.getTestSuiteStatus()
	response = myTestApi.importCSV(csvFileName,"myNewTemplateName")
	if response.isCompleted() and not response.hasError() and response.getStatus():
		newUUID = response.getMessage()
		myTestApi.runTestSuite(newUUID)
		time.sleep(1)
		loop = True
		while loop:
			response = myTestApi.getTestSuiteStatus()
			if response.getMessage() == "Done":
				loop = False
			time.sleep(2)
	response = myTestApi.getTestSuiteResults()
	resultsList = response.getRetrievedObject()
	for myResult in resultsList:
		print myResult
	myTestApi.tearDownTest()
	myTestApi.closeSession()
	
# export a CSV file
if csvExport:
	myTestApi.newSession()
	myTestApi.exportCSV("12345-bad-uuid-678910")
	myTestApi.exportCSV(scenarioUUID)
	myTestApi.exportCSV(testSuiteUUID)
	myTestApi.exportCSV(testSuiteUUID,'MyCsv.csv')
	response = myTestApi.importCSV('MyCsv2.csv',"myNewTemplateName")
	print 'New UUID = '+response.getMessage()
	myTestApi.exportCSV(response.getMessage(),'MyCsv3.csv')

	myTestApi.closeSession()
	
if finalClose:
	myTestApi.closeAllSessions()
	
	
if doPcaps:
	# get/stop a capture
	myRestApi.getCapture(jobId,pcapName)